package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.bean.User;
import org.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;
@Slf4j
@Controller
public class LoginController {

    @Autowired
    UserService userService;

    @RequestMapping("/user/login")
    public String doLogin(User user, Map<String, Object> map, HttpSession
            session){
        // 从数据库中查询用户信息
        User loginUser = userService.getByUserNameAndPassword(user);
        if(loginUser != null){
            session.setAttribute("loginUser", user);
            log.info("登录成功，用户名："+ user.getUsername());
// 防止重复提交使用重定向
            return "redirect:/main.html";
        } else {
            map.put("msg", "用户名或密码错误");
            log.error("登录失败");
            return "login";
        }

    }

    @RequestMapping("/user/logout")
    public String dologout(HttpSession session) {
//        跳转到登录页面
//        清除session loginUser
        session.removeAttribute("loginUser");
        return "login";

    }

//    注册用户
    @RequestMapping("/user/registration")
    public String doregistration(User user, @RequestParam("repassword") String repassword, Map<String, Object> map, HttpSession
            session) {
        User singuser = userService.getUser2(user.getUsername());
//        System.out.println(user.getPassword());
//        System.out.println(user.getPassword());
//        System.out.println(singuser);
//        检查密码是否一致
        if (!repassword.equals(user.getPassword())){
            map.put("msg", "密码不一致");
            log.error("注册失败");
            return "registration";
        }
        else if (repassword==""||user.getPassword()==""||user.getUsername()==""||user.getEmail()==""){
            map.put("msg", "请填写信息");
            log.error("注册失败");
            return "registration";
        }
        else if(singuser!= null){
//            检查用户是否存在
            map.put("msg", "用户已存在.请更换用户名");
            log.error("注册失败");
            return "registration";
        }
//        注册用户
        int i = userService.insUser2(user);
        if (i==1){
            map.put("msg", "注册成功，请在登录页面重新登录");
            log.info("注册成功");
            return "login";
        }else {
            map.put("msg", "注册失败");
            log.error("注册失败");
            return "registration";
        }


    }


}
